﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Newtonsoft.Json;
using QG.FrontDesk.BLL.IService;
using QG.FrontDesk.com.Attbutes;
using QG.FrontDesk.com.Models;
using QG.FrontDesk.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace QG.FrontDesk.com.Controllers
{
    public class PersonController : Controller
    {
        ResponseResult responseResult = new ResponseResult();


        private IResumesByPersonService _resumesByPersonService;

        private IResumeService _resumeService;
        public PersonController(IResumeService resumeService, IResumesByPersonService resumesByPersonService)
        {
            DataContext<Company>.context.model = null;
            DataContext<UserInfo>.context.model = null;
            //获取存在的cookie
            //再次浏览器判断是否有值
            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            if (cookie != null)
            {
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                string userData = ticket.UserData;
                if (ticket.Name == "求职")
                {
                    DataContext<UserInfo>.context.model = JsonConvert.DeserializeObject<UserInfo>(userData);
                }
                else if (ticket.Name == "公司")
                {
                    DataContext<Company>.context.model = JsonConvert.DeserializeObject<Company>(userData);
                }
            }
            _resumesByPersonService = resumesByPersonService;
            this._resumeService = resumeService;
        }

        /// <summary>
        /// 编写简历页面
        /// </summary>
        /// <returns></returns>
        [PermissionAttribute]
        public ActionResult Jianli()
        {
            List<Cityinfo> cityinfo = _resumeService.GetCityinfos();
            ViewBag.cityinfo = cityinfo;
            int Id = DataContext<UserInfo>.context.model.UserId;
            ResumeInfo resume = _resumeService.GetResumeInfo(Id) ?? new ResumeInfo();
            //DataContext<ResumeInfo>.context.model = resume;
            ViewBag.resume = resume;

            //根据id 查询工作经历表            
            Businessexperien busin = _resumeService.GetBusinessexperien(resume.ExperId) ?? new Businessexperien();
            //DataContext<Businessexperien>.context.model = busin;
            ViewBag.busin = busin;

            return View();
        }


        /// <summary>
        /// 修改“用户信息”
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public JsonResult UpdateUserInfo(UserInfo userInfo)
        {
            responseResult.success = _resumeService.UpdateUserInfo(userInfo) > 0;
            return Json(responseResult);
        }

        /// <summary>
        /// 修改“期望工作表”
        /// </summary>
        /// <param name="expecttoWork"></param>
        /// <returns></returns>
        public JsonResult UpdateExpectToWork(ExpecttoWork expecttoWork)
        {
            responseResult.success = _resumeService.UpdateExpectToWork(expecttoWork) > 0;
            return Json(responseResult);
        }

        /// <summary>
        /// 修改“工作经历表”
        /// </summary>
        /// <param name="businessexperien"></param>
        /// <returns></returns>
        public JsonResult UpdateBusinessexperien(Businessexperien businessexperien)
        {
            responseResult.success = _resumeService.UpdateBusinessexperien(businessexperien) > 0;
            return Json(responseResult);
        }

        /// <summary>
        /// 修改“项目经验表”
        /// </summary>
        /// <param name="projectExperien"></param>
        /// <returns></returns>
        public JsonResult UpdateProjectExperien(ProjectExperien projectExperien)
        {
            responseResult.success = _resumeService.UpdateProjectExperien(projectExperien) > 0;
            return Json(responseResult);
        }

        /// <summary>
        /// 修改“教育背景表”
        /// </summary>
        /// <param name="educational"></param>
        /// <returns></returns>
        public JsonResult UpdateEducation(Educational educational)
        {
            responseResult.success = _resumeService.UpdateEducation(educational) > 0;
            return Json(responseResult);
        }

        /// <summary>
        /// 修改“作品展示表”
        /// </summary>
        /// <param name="worksShow">作品展示表</param>
        /// <returns></returns>
        public JsonResult UpdateWorksShow(WorksShow worksShow)
        {
            responseResult.success = _resumeService.UpdateWorksShow(worksShow) > 0;
            return Json(responseResult);
        }

        /// <summary>
        /// 新增简历附件（文件上传）
        /// </summary>
        /// <param name="resumeInfo"></param>
        /// <returns></returns>
        public JsonResult AddResumePath(ResumeInfo resumeInfo)
        {
            responseResult.success = _resumeService.AddResumePath(resumeInfo) > 0;
            return Json(responseResult);
        }

        /// <summary>
        /// 查看简历页面
        /// </summary>
        /// <returns></returns>
        [PermissionAttribute]
        public ActionResult Preview(Nullable<int> UserId)
        {
            UserInfo userInfo = DataContext<UserInfo>.context.model;
            int id = userInfo == null ? UserId??0: userInfo.UserId;
            ResumeInfo resume = _resumeService.GetResumeInfo(id) ?? new ResumeInfo();

            //DataContext<ResumeInfo>.context.model = resume;
            ViewBag.resume = resume;
            return View();
        }


        /// <summary>
        /// 已投递简历页面
        /// </summary>
        /// <returns></returns>
        [PermissionAttribute]
        public ActionResult Delivery(int page = 1, short statu = -1)
        {
            List<Position_ResumeInfo> resumes = _resumesByPersonService.GetResumeInfo(DataContext<UserInfo>.context.model.UserId, statu);
            ViewBag.Count = resumes.Count % 10 > 0 ? resumes.Count / 10 + 1 : resumes.Count / 10;//总页数
            ViewBag.resumes = resumes.Skip((page - 1) * 3).Take(3).ToList();//进行筛选分页
            ViewBag.curr = page;//当前页数            
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public FileResult ExportWord(string html, int type, string name)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<!DOCTYPE html>");
            sb.Append("<body>");
            sb.Append(html);
            sb.Append("</body>");
            var byteArray = System.Text.Encoding.Default.GetBytes(sb.ToString());
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            string contentType = "";
            string suffix = "";
            if (type == 1)
            {
                contentType = "application/ms-word";
                suffix = ".doc";
            }
            else if (type == 2)
            {
                contentType = "text/html";
                suffix = ".html";
            }
            else
            {
                contentType = "application/pdf";
                suffix = ".pdf";
                byteArray = ConvertHtmlTextToPDF(html);
            }
            return File(byteArray, contentType, name + "的简历" + suffix);
        }

        /// <summary>
        /// 将Html文字 输出到PDF档里
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        public byte[] ConvertHtmlTextToPDF(string htmlText)
        {
            if (string.IsNullOrEmpty(htmlText))
            {
                return null;
            }
            htmlText = htmlText.Replace("<br>", "").Replace("<hr>", "").Replace("<img>", "").Replace("<param>", "").Replace("<link>", "");
            MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流
            byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串转成byte[]
            MemoryStream msInput = new MemoryStream(data);
            Document doc = new Document();
            doc.SetMargins(0, 0, 0, 0);     //设置内容边距
            PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
            //指定文件预设开档时的缩放为100%
            PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
            //开启Document文件 
            doc.Open();
            #region pdf文件添加LOGO
            //string logoPath = Server.MapPath("/Assets/images/tuanzi.jpg");
            //Image logo = Image.GetInstance(logoPath);
            //float scalePercent = 10f;       //图片缩放比例
            //float percentX = 60f;
            //float percentY = 250f;
            //logo.ScalePercent(scalePercent);
            //logo.SetAbsolutePosition(percentX, doc.PageSize.Height - percentY);
            //doc.Add(logo);
            #endregion
            //使用XMLWorkerHelper把Html parse到PDF档里
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
            //将pdfDest设定的资料写到PDF档
            PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
            writer.SetOpenAction(action);
            doc.Close();
            msInput.Close();
            outputStream.Close();
            //回传PDF档案 
            return outputStream.ToArray();
        }


    }
}